package com.example.piece.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import com.therouter.router.Autowired
import com.therouter.router.Route
import com.cjt2325.cameralibrary.JCameraView
import com.cjt2325.cameralibrary.listener.ErrorListener
import com.cjt2325.cameralibrary.listener.JCameraListener
import com.example.base.ext.addWatermarkToBottomCenter
import com.example.base.ext.finishWithResult
import com.example.base.ext.saveTo
import com.example.base.ext.toast
import com.example.base.ui.activity.BaseActivity
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.ActivityCameraBinding
import java.io.File
import java.util.*


@Route(path = RoutePath.MAIN_CAMERA)
class CameraActivity : BaseActivity<ActivityCameraBinding>(), ErrorListener, JCameraListener {

    /**  地理位置信息  **/
    @JvmField
    @Autowired(name = Key.DataKey.LOCATION_DESCRIBE)
    var locationDescribe: String? = null

    /**  异常信息字段名  **/
    @JvmField
    @Autowired(name = Key.DataKey.ABNORMAL_FIELD_NAME)
    var abnormalFieldName: String? = null

    /**  异常信息字段id  **/
    @JvmField
    @Autowired(name = Key.DataKey.ABNORMAL_FIELD_ID)
    var abnormalFieldId: String? = null

    override fun getContentRes(): Int = R.layout.activity_camera

    @Suppress("DEPRECATION")
    private val savePath: String by lazy {
        // getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path ?: ""

        if (Build.VERSION.SDK_INT > 29) {
            getExternalFilesDir(null)!!.getAbsolutePath()
        } else {
            Environment.getExternalStorageDirectory().path
        }


    }

    /**  全屏设置  **/
    @SuppressLint("ObsoleteSdkInt")
    private fun fullScreen() {
        if (Build.VERSION.SDK_INT >= 19) {
            window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        } else {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        fullScreen()

        // set default config
        mBinding.jCameraView.setSaveVideoPath(savePath)
        mBinding.jCameraView.setFeatures(JCameraView.BUTTON_STATE_BOTH)
        mBinding.jCameraView.setMediaQuality(JCameraView.MEDIA_QUALITY_MIDDLE)

        mBinding.jCameraView.setErrorLisenter(this)
        mBinding.jCameraView.setJCameraLisenter(this)

        mBinding.jCameraView.setLeftClickListener {
            this@CameraActivity.finish()
        }
    }

    override fun recordSuccess(url: String?, firstFrame: Bitmap?) {

        // 当前时间的时间戳
        val date = Date()

        // 若字段 id 不为空, 则按照 字段id_时间戳_cover.jpg 的方式命名第一帧
        val fileName =
            if (null != abnormalFieldId) "${abnormalFieldId}_${Date().time}_cover.jpg"
            else "${date.time}_cover.jpg"

        // 若位置信息与异常字段名不为空, 则给视频第一帧加上水印
        if ((null != locationDescribe) and (null != abnormalFieldName))
            firstFrame?.addWatermarkToBottomCenter("${abnormalFieldName}\n${locationDescribe}")
                ?.saveTo(
                    savePath,
                    fileName
                )
        else
            firstFrame?.saveTo(savePath, fileName)

        // toast("录像完毕，路径为：$url")


        // 若异常字段 id 不为空, 则重新命名视频文件, 规则为 字段id_时间戳.mp4
        val videoFile = File(url ?: "")
        val newVideoPath =
            "${videoFile.parent}${File.separator}${
                abnormalFieldId
                    ?: ""
            }${if (abnormalFieldId != null) "_" else ""}${date.time}.mp4"
        videoFile.renameTo(File(newVideoPath))

        MediaScannerConnection.scanFile(
            getApplicationContext(),
            arrayOf(newVideoPath),
            null,
            null
        )

        Log.e(
            "CameraActivity",
            "录像完毕，视频路径为：${newVideoPath} , 封面路径为：$savePath${File.separator}$fileName"
        )


        // 传递需要带回的参数
        finishWithResult(
            mutableMapOf(
                Key.DataKey.IS_VIDEO to true,
                Key.DataKey.COVER_PATH to "$savePath${File.separator}$fileName",
                Key.DataKey.VIDEO_PATH to (newVideoPath)
            )
        )
    }

    override fun captureSuccess(bitmap: Bitmap?) {

        // 若字段 id 不为空, 则按照 字段id_时间戳.jpg 的方式命名第一帧
        val fileName =
            if ((null != abnormalFieldId)) "${abnormalFieldId}_${Date().time}.jpg"
            else "${Date().time}.jpg"

        // 若位置信息与异常字段名不为空, 则给图片加上水印
        if ((null != locationDescribe) and (null != abnormalFieldName))
            bitmap?.addWatermarkToBottomCenter("${abnormalFieldName}\n${locationDescribe}")?.saveTo(
                savePath,
                fileName
            )
        else
            bitmap?.saveTo(savePath, fileName)

        Log.e("CameraActivity", "拍照完毕，路径为：$savePath${File.separator}$fileName")
        // toast("拍照完毕, 路径为：$savePath${File.separator}$fileName")
        //发送广播更新图片

        val values = ContentValues()
        values.put(MediaStore.Images.Media.DATA, "$savePath${File.separator}$fileName")
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        val uri: Uri? = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values
        )

        sendBroadcast(
            Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + "$savePath${File.separator}$fileName")
            )
        ) //path_export是你导出的文件路径


        // 传递需要带回的参数
        val intent = Intent()
        intent.putExtra(Key.DataKey.IS_VIDEO, false)
        intent.putExtra(Key.DataKey.IMAGE_PATH, "$savePath${File.separator}$fileName")
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun AudioPermissionError() {
        toast("打开相机失败！")
    }

    override fun onError() {
        toast("没有录像权限！")
    }

    override fun onResume() {
        super.onResume()
        mBinding.jCameraView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.jCameraView.onPause()
    }


}